#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Tkinter import Label, Entry, Button, Tk, StringVar, Text
from LexicalAnalysis import LexicalAnalysis
import LR1Grammar
import tkFileDialog
import SetUp
import re

def select():
    select = Tk()
    path = StringVar()
    Label(select, text="文件路径", font=("Arial", 12)).grid(row = 0, column = 0)
    Entry(select, textvariable = path).grid(row = 0, column = 1)
    Button(select, text = "...", font=("Arial", 12), command = selectPath).grid(row = 0, column = 2)
    Button(select, text = "打开", font=("Arial", 12), command = textUpdate).grid(row = 1, column = 1)
    Button(select, text = "退出", font=("Arial", 12), command = select.destroy).grid(row = 1, column = 2)
    select.mainloop()

def selectPath():
    path_ = tkFileDialog.askopenfilename(filetypes=[("bmp".decode('gbk'),"*")])
    path.set(path_)

def textUpdate():
    filePath = path.get()
    content = open(filePath)
    lines = content.readlines()
    t1.delete('0.0', 'end')
    for line in lines:
        t1.insert('insert', line)
    t1.update()

def analysis():
    text = t1.get('0.0', 'end')
    Input = list(str(text))
    content = ''
    for t in Input:
        if t == '\t' or t == '\n' or t == '\r':
            continue
        else:
            content += str(t)
    result, turples = analysisor.analysis(content)
    # print turples
    turpleTrans = ''
    for t in turples:
        if re.match(r'(\d+)', t[0]) != None:
            turpleTrans += t[1] + ' '
        elif re.match(r'(IDN)', t[0]) != None:
            turpleTrans += 'obj '
        elif re.match(r'(number)', t[0]) != None:
            turpleTrans += 'num '
    # print turpleTrans
    t2.delete('0.0', 'end')
    for line in result:
        t2.insert('insert', line + '\n')
    t2.update()
    parse_table = LR1Grammar.getParseTable()
    LR1Grammar.parse_inputs(parse_table, turpleTrans)


if __name__ == "__main__":
    DFASet = SetUp.loadRegex()
    analysisor = LexicalAnalysis(DFASet)
    root = Tk()
    t1 = Text(root, height=30, width=30, font=("Courier 10 Pitch", 12))
    t1.grid(row = 0, column = 0)
    path = StringVar()
    Button(root, text = "从文件打开", font=("Arial", 12), command = select).grid(row = 1, column = 0)
    Button(root, text = "词法分析", font=("Arial", 12), command = analysis).grid(row = 1, column = 1)
    Button(root, text = "语法分析", font=("Arial", 12), command = analysis).grid(row = 1, column = 2)
    t2 = Text(root, height=30, width=30, font=("Courier 10 Pitch", 12))
    t2.grid(row = 0, column = 1)
    t3 = Text(root, height=30, width=30, font=("Courier 10 Pitch", 12))
    t3.grid(row = 0, column = 2)
    root.mainloop()
